package yanglib.application.metadata.server;

import yanglib.application.metadata.message.GetMessage;
import yanglib.application.metadata.message.GetReplyMessage;
import yanglib.application.metadata.message.PutMessage;
import yanglib.application.metadata.message.PutReplyMessage;
import yanglib.message.Message;
import yanglib.network.MessageHandler;
import yanglib.network.Network;
import yanglib.test.network.TestMessage;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 9/5/14
 * Time: 3:51 PM
 * To change this template use File | Settings | File Templates.
 */
public class ServerMessageHandler implements MessageHandler {

    private Network network = null;
    private MemStorage storage = null;
    private int selfID;

    public ServerMessageHandler(int selfID, String logPath) {
        this.selfID = selfID;
        this.storage = new MemStorage(logPath);
    }

    public void setNetwork(Network network) {
        this.network = network;
    }

    @Override
    public void handleMessage(Message message) {
        try{
            if (message instanceof PutMessage) {
                PutMessage putMessage = (PutMessage) message;
                storage.put(putMessage.getKey(), putMessage.getValue());
                try {
                    network.send(new PutReplyMessage(selfID, putMessage.getRequestID(), true), message.getSender());
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            else if(message instanceof GetMessage){
                GetMessage getMessage = (GetMessage)message;
                byte[] ret = storage.get(getMessage.getKey());
                try {
                    network.send(new GetReplyMessage(selfID, getMessage.getRequestID(), getMessage.getKey(), ret), message.getSender());
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
        catch(IOException e){
            e.printStackTrace();
            System.exit(-1);
        }
    }
}
